package yixingren.bonus;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Paint.Style;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import yixingren.magicfinger.CommonVariables;
import yixingren.magicfinger.R;

public class GuaGuaKa extends View {

	/**
	 * 绘制线条的Paint,即用户手指绘制Path
	 */
	private Paint linePainter = new Paint();
	/**
	 * 记录用户绘制的Path
	 */
	private Path linePath = new Path();
	/**
	 * 内存中创建的Canvas
	 */
	private Canvas mCanvas;

    private Paint paint = new Paint();

    /**
	 * mCanvas绘制内容在其上
	 */
	private Bitmap mBitmap;	
	private Bitmap rainBitmap;
	/**
	 * 下面两个变量是控制吹气和画完的主要标志位，之后会根据其状态，针对的刷新UI
	 */	
	private volatile boolean isBlow = false;
    private boolean isBlewOnce = false;
	
	/**
	 * 以下是奖区的一些变量，但是在这次程序中没有使用到。。因为和源程序还有联系……所以暂时没有删除
	 */
	private Paint backgroundPainter = new Paint();
	private Rect mTextBound = new Rect();
	private String mText = "￥500,0000";

	private int mLastX;
	private int mLastY;

    private final String LOG_TAG = "GuaGuaKa";

	public GuaGuaKa(Context context) {
		this(context, null);
	}

	public GuaGuaKa(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public GuaGuaKa(Context context, AttributeSet attrs, int defStyle) {

		super(context, attrs, defStyle);
		init();
	}
	
	/**
	 * 初始化，这里我们把path，microphone和bitmap都进行了初始化。
	 * 当然，我们麦克风监听线程也同时初始化好了。
	 */
	private void init() {

		linePath = new Path();

        Log.d(LOG_TAG, "trackedId: " + CommonVariables.trackedId);

		rainBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.rain);
//		mic = new Microphone();
		initLinePainter();
		initBackgroundPainter();
//		initBackThread();
	}

	/**
	 * 初始化canvas的绘制用的画笔
	 */
	private void initBackgroundPainter() {

		backgroundPainter.setStyle(Style.FILL);
		backgroundPainter.setTextScaleX(2f);
		backgroundPainter.setColor(Color.DKGRAY);
		backgroundPainter.setTextSize(32);
		backgroundPainter.getTextBounds(mText, 0, mText.length(), mTextBound);
	}

    /**
     * 设置画笔的一些参数
     */
    private void initLinePainter() {

        // 设置画笔
        // linePainter.setAlpha(0);
        linePainter.setColor(Color.parseColor("#c0c0c0"));
        linePainter.setAntiAlias(true);
        linePainter.setDither(true);
        linePainter.setStyle(Style.STROKE);
        linePainter.setStrokeJoin(Paint.Join.ROUND); // 圆角
        linePainter.setStrokeCap(Paint.Cap.ROUND); // 圆角
        // 设置画笔宽度
        linePainter.setStrokeWidth(100);
    }

	@Override
	protected void onDraw(Canvas canvas) {

        int width = getMeasuredWidth();
        int height = getMeasuredHeight();
        paint.setAlpha(0xa0);
        drawPath();
        canvas.drawBitmap(mBitmap, 0, 0, null);

        /**
         * 其实我这里还有有地方没有处理好，第一吹气完后立马触摸屏幕，会从左上角来一条线，
         * 第二感觉刷新很占资源感觉迟钝不自然
         */
        if (isBlow) {
            Log.d(LOG_TAG, "isBlew");
            linePath.reset();
            mCanvas.drawBitmap(rainBitmap, null, new RectF(0, 0, width, height), paint);
            isBlow=false;
        }
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		
		int width = getMeasuredWidth();
		int height = getMeasuredHeight();
		paint.setAlpha(0xc0);
		// 初始化bitmap
		mBitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);
		mCanvas = new Canvas(mBitmap);

		// 绘制遮盖层
		// mCanvas.drawColor(Color.parseColor("#c0c0c0"));
		linePainter.setStyle(Style.FILL);
//		mCanvas.drawRoundRect(new RectF(0, 0, width, height), 30, 30,
//				linePainter);
		//这个速度就慢了。。。不是立即感觉到的
//		mCanvas.drawBitmap(rainBitmap, null, new RectF(0, 0, width, height), paint);//需要一张半透明的图片,利用透明度修改好饿了
	}

	/**
	 * 绘制线条
	 */
	private void drawPath() {

		linePainter.setStyle(Style.STROKE);
		linePainter.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
		mCanvas.drawPath(linePath, linePainter);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {

        if (!isBlewOnce)
            return true;

		int action = event.getAction();
		int x = (int) event.getX();
		int y = (int) event.getY();
		
		switch (action) {

		case MotionEvent.ACTION_DOWN:
			mLastX = x;
			mLastY = y;
			linePath.moveTo(mLastX, mLastY);
			break;
		case MotionEvent.ACTION_MOVE:

			int dx = Math.abs(x - mLastX);
			int dy = Math.abs(y - mLastY);

			if (dx > 3 || dy > 3)
				linePath.lineTo(x, y);

			mLastX = x;
			mLastY = y;
			break;
		case MotionEvent.ACTION_UP:
			new Thread(sumWipedAreaRunnable).start();
			break;
		}
		
		invalidate();
		return true;
	}

	/**
	 * 统计擦除区域任务
	 */
	private Runnable sumWipedAreaRunnable = new Runnable() {

		private int[] mPixels;

		@Override
		public void run() {

			int w = getWidth();
			int h = getHeight();

			float wipeArea = 0;
			float totalArea = w * h;

			Bitmap bitmap = mBitmap;

			mPixels = new int[w * h];

			/**
			 * 拿到所有的像素信息
			 */
			bitmap.getPixels(mPixels, 0, w, 0, 0, w, h);

			/**
			 * 遍历统计擦除的区域
			 */
			for (int i = 0; i < w; i++) {
				for (int j = 0; j < h; j++) {

					int index = i + j * w;
					if (mPixels[index] == 0) {
						wipeArea++;
					}
				}
			}

			/**
			 * 根据所占百分比，进行一些操作
			 */
			if (wipeArea > 0 && totalArea > 0) {

				int percent = (int) (wipeArea * 100 / totalArea);
				Log.e("TAG", percent + "");

				if (percent > 60) {
					Log.e("TAG", "清除区域达到60%，下面自动清除");

                    listener.wiped();
					postInvalidate();
				}
			}
		}
	};

    public void setBlew() {

        Log.d(LOG_TAG, "setBlew");
        isBlow = true;
        isBlewOnce = true;
        invalidate();
    }

    private OnWipedListener listener;
    public void setOnWippedListener(OnWipedListener listener) {

        this.listener = listener;
    }

    public interface OnWipedListener {

        void wiped();
    }
}